
package com.x52im.rbchat.logic.chat_root.impl;

import android.app.Activity;
import android.content.Context;
import android.text.SpannableString;
import android.text.style.DynamicDrawableSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.eva.android.widget.WidgetUtils;
import com.eva.epc.common.util.CommonUtils;
import com.x52im.rainbowchat.http.logic.dto.RosterElementEntity;
import com.x52im.rainbowchat.im.dto.ChatType;
import com.x52im.rainbowchat.im.dto.QuoteMeta;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.R;
import com.x52im.rbchat.cache.GroupsProvider;
import com.x52im.rbchat.logic.chat_root.face.EmojiUtil;
import com.x52im.rbchat.logic.chat_root.model.Message;
import com.x52im.rbchat.logic.chat_root.model.MessageExt;

/**
 * 聊天界面中输入框下方的被引用消息内容显示组件逻辑封装类。
 *
 * @author JackJiang
 * @since 11.0
 */
public class Quote4InputWrapper {

    private final static String TAG = Quote4InputWrapper.class.getSimpleName();

    private Activity parentActivity = null;

    private ViewGroup quoteLayout = null;
    private TextView quoteContentView = null;
    private ImageView quoteCancelView = null;

    private Message beQuoteMessage = null;

    public Quote4InputWrapper(Activity parentActivity) {
        this.parentActivity = parentActivity;

        initViews();
        initListeners();
    }

    protected void initViews() {
        quoteLayout = parentActivity.findViewById(R.id.chatting_list_view_input_quoteLL);
        quoteContentView = parentActivity.findViewById(R.id.chatting_list_view_input_quoteContentView);
        quoteCancelView = parentActivity.findViewById(R.id.chatting_list_view_input_quoteCancelBtn);
    }

    protected void initListeners() {
        quoteCancelView.setOnClickListener(v -> cancelQuote());
    }

    /**
     * 点击消息气泡中"引用"菜单项后执行的消息引用逻辑。
     *
     * @param chatType 聊天类型
     * @param toId 聊天对象id
     * @param beQuoteMessage 被引用消息对象
     */
    public void doQuote(int chatType, String toId, Message beQuoteMessage) {
        if(beQuoteMessage != null) {
            this.beQuoteMessage = beQuoteMessage;

            this.quoteLayout.setVisibility(View.VISIBLE);

            String messageContentForShow = "";
            if(beQuoteMessage.getText() != null) {
                // 消息内容的显示（比如图片消息会显示"[图片]"这样的字串）
                messageContentForShow = MessageExt.parseMessageContentPreview(parentActivity, beQuoteMessage.getText(), beQuoteMessage.getMsgType());
            } else {
                messageContentForShow = parentActivity.getResources().getString(R.string.general_unknow_content);
            }

            String sendderNick = getQuoteNick(parentActivity, chatType, toId, beQuoteMessage.getSenderId(), beQuoteMessage.getSenderDisplayName());
            String toShow = (!CommonUtils.isStringEmpty(sendderNick) ? sendderNick +"：" : "")+messageContentForShow;

            // FFF emoji图片表情转换
            SpannableString ss = EmojiUtil.replaceEmoticons(parentActivity, toShow, 50, 50, DynamicDrawableSpan.ALIGN_BOTTOM);
            this.quoteContentView.setText(ss);
        } else {
            WidgetUtils.showWithDialog(parentActivity
                    , parentActivity.getResources().getString(R.string.general_prompt)
                    , parentActivity.getResources().getString(R.string.general_invalid_data) );
        }
    }

    public void cancelQuote() {
        this.quoteLayout.setVisibility(View.GONE);
        this.quoteContentView.setText(null);
        this.beQuoteMessage = null;
    }

    /**
     * 返回本次引用消息的无数据对象（用于消息发送时使用）。
     *
     * @param chatType 聊天类型
     * @param toId 聊天对象id
     * @return 返回新的QuoteMeta对象
     */
    public QuoteMeta getQuoteMeta(int chatType, String toId) {
        QuoteMeta quoteMeta = null;
        if(this.beQuoteMessage != null) {
            quoteMeta = new QuoteMeta();

            // 如果是群聊，则存放的是被引用群聊消息被服务端扩散写前的原始指纹码（也就是群成员收到的此条群聊消息的父指纹码）
            quoteMeta.setQuote_fp(chatType == ChatType.CHAT_TYPE_GROUP$CHAT
                    ? this.beQuoteMessage.getFingerPrintOfParent() : this.beQuoteMessage.getFingerPrintOfProtocal());
            quoteMeta.setQuote_sender_uid(this.beQuoteMessage.getSenderId());

            String sendderNick = beQuoteMessage.getSenderDisplayName();//getQuoteNick(parentActivity, chatType, toId, beQuoteMessage.getSenderId(), beQuoteMessage.getSenderDisplayName());
            if(this.beQuoteMessage.isOutgoing()) {
                RosterElementEntity localUser = MyApplication.getInstance2().getIMClientManager().getLocalUserInfo();
                if (localUser != null)
                    sendderNick = localUser.getNickname();
            }

            quoteMeta.setQuote_sender_nick(sendderNick);
            quoteMeta.setQuote_content(this.beQuoteMessage.getText());
            quoteMeta.setQuote_type(this.beQuoteMessage.getMsgType());
        }
        return quoteMeta;
    }

    public static String getQuoteNick(Context c, int chatType, String toId, String quoteSenderId, String quoteSenderNick) {
        if(quoteSenderId !=  null) {
            try {
                String sendderNick = quoteSenderNick;
                // 如果是"我"发出的消息
                if (Message.isOutgoing(quoteSenderId)) {
                    if (chatType == ChatType.CHAT_TYPE_GROUP$CHAT) {
                        sendderNick = GroupsProvider.getMyNickNameInGroupEx(c, toId);
                    } else {
                        RosterElementEntity localUser = MyApplication.getInstance2().getIMClientManager().getLocalUserInfo();
                        if (localUser != null)
                            sendderNick = localUser.getNickname();
                    }
                } else {
                    // 优先尝试从好友数据中读取好友信息
                    RosterElementEntity friendRee = MyApplication.getInstance2().getIMClientManager().getFriendsListProvider().getFriendInfoByUid2(quoteSenderId);
                    // 是好友
                    if(friendRee != null) {
                        sendderNick = friendRee.getNickNameWithRemark();
                    }
                }

                return sendderNick;
            } catch(Exception e) {
                Log.w(TAG, e);
            }
        }
        return null;
    }

}
